﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO.Ports;

namespace simu485.Views
{
    public class C485Uart
    {
        private SerialPort? com;
        private C485Log log;
        //public System.Threading.Thread ReadThread;
        public bool Open(string port, C485Log log)
        {
            this.log = log;
            com = new SerialPort(port);
            com.BaudRate = 115200;
            com.Parity = Parity.None;
            com.StopBits = StopBits.One;
            com.DataBits = 8;
            //com.DataReceived += Recv;
            //com.ReceivedBytesThreshold = 4;
            com.WriteTimeout = 10;
            com.ReadTimeout = 5;

            com.Open();
            return true;
        }
        public bool Close()
        {
            com.Close();
            return true;
        }

        public void Send(byte[] buf)
        {
            if (com.IsOpen)
            {
                try
                {
                    com.Write(buf, 0, buf.Length);
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.ToString());
                }
            }
            log.AddItem(buf, buf.Length, 1);
        }

        //public byte[] rx_buf = new byte[4096];

        //private int _rx_cnt = 0;
        //public int rx_cnt
        //{
        //    get { return _rx_cnt; }
        //    set
        //    {
        //        _rx_cnt = value;
        //    }
        //}

        public int Recv(byte[] rx_buf, int offset, int len)
        {
            try
            {
                return com.Read(rx_buf, offset, len);
            }
            catch (Exception excp)
            {
                Console.WriteLine("uart read Error: {0}", excp.Message);
                return 0;
            }
            //if(rx_cnt > 0)
            //{
            //    byte[] rx_data = new byte[rx_cnt];
            //    Array.Copy(rx_buf, rx_data, rx_cnt);
            //    log.AddItem(rx_data, 0);
            //}
        }
    }
}
